package com.pms.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.pms.cache.annotation.Cache;
import com.pms.cache.annotation.CacheClear;
import com.pms.entity.ChargeTemplate;
import com.pms.entity.ChargeValue;
import com.pms.exception.RRException;
import com.pms.mapper.ChargeTemplateMapper;
import com.pms.mapper.ChargeValueMapper;
import com.pms.service.IChargeTemplateService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.pms.service.IChargeValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ASUS_B
 * @since 2017-11-07
 */
@Service
public class ChargeTemplateServiceImpl extends BaseServiceImpl<ChargeTemplateMapper, ChargeTemplate> implements IChargeTemplateService {
    @Autowired
    IChargeValueService chargeValueService;

    @Transactional
    @CacheClear(pre="chargeTemplate")
    public void updateChargeTemplate(ChargeTemplate template){
        baseMapper.updateById(template);
        chargeValueService.delete(new EntityWrapper<ChargeValue>().eq("charge_template_id", template.getChargeTemplateId()));
        chargeValueService.insertBatch(template.getTemplateDetail());

    }

    @Transactional
    @CacheClear(pre="chargeTemplate")
    public void addChargeTemplate(ChargeTemplate template){
        baseMapper.insert(template);
        chargeValueService.insertBatch(template.getTemplateDetail());

    }

    @Cache(key="chargeTemplate:selectChargeTemplateInfo{chargeTemplateId}")
    public ChargeTemplate selectChargeTemplateInfo(Long chargeTemplateId){
        ChargeTemplate chargeTemplate = baseMapper.selectById(chargeTemplateId);
       if(null==chargeTemplate){
          throw  new RRException("暂无该收费模板信息",400);
       }
        List<ChargeValue> chargeValueList = chargeValueService.selectList(new EntityWrapper<ChargeValue>().eq("charge_template_id", chargeTemplateId));
        if (null == chargeValueList) {
            chargeValueList = new ArrayList<ChargeValue>();
        }
        chargeTemplate.setTemplateDetail(chargeValueList);
        return chargeTemplate;
    }
}
